package welsir.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import welsir.entity.dos.Article;
import welsir.entity.dos.ArticleClass;
import welsir.entity.dos.ArticleComment;
import welsir.entity.vo.ArticlePageVO;
import welsir.entity.vo.ResultMessage;
import welsir.mapper.ArticleClassMapper;
import welsir.mapper.ArticleCommentMapper;
import welsir.mapper.ArticleMapper;
import welsir.security.annotations.Authentication;
import welsir.security.enums.UserEnums;
import welsir.service.IArticleService;
import welsir.util.MathUtil;
import welsir.util.ResultUtil;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.UUID;

/**
 * @author Genius
 * @date 2023/03/07 22:28
 * 后台文章管理
 * @admin 需要管理员权限
 **/
@Api(value = "文章后台管理Controller",tags = {"文章后台管理接口"})
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private IArticleService articleService;

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private ArticleClassMapper articleClassMapper;

    @Resource
    private ArticleCommentMapper articleCommentMapper;

    /**
     * 新建文章
     * @param article
     * @return
     * @throws ParseException
     */
    @ApiOperation(value = "新建文章")
    @Authentication(role = UserEnums.ADMIN)
    @PostMapping("/create")
    public ResultMessage<Object> add(@RequestBody Article article) {
        //生成随机数注入
        article.setArticleStatus(MathUtil.randomDigitNumber(7));

        article.setArticleId(String.valueOf(MathUtil.randomDigitNumber(8)));


        article.setAddTime(article.getCreateTime());

        //查询分类名称对应的id值
        QueryWrapper<ArticleClass> wrapper= new QueryWrapper<ArticleClass>();
        wrapper.eq("name", article.getSortClass());
        ArticleClass articleClass = articleClassMapper.selectOne(wrapper);

        article.setSortClass(articleClass.getId().toString());
        //saveOrUpdate:要在插入数据库时，如果有某一个主要字段的值重复，则不插入，否则则插入！

        if (articleService.saveOrUpdate(article)) {
            return ResultUtil.data(article);
        }else{
            return ResultUtil.error(500,"插入失败");
        }

    }


    /**
     * 根据id删除文章
     * @param id
     * @return
     */
    @ApiOperation(value = "根据uid删除文章")
    @Authentication(role = UserEnums.ADMIN)
    @GetMapping("/deleteArticleById/{article_id}")
    public ResultMessage<Boolean> deleteArticleById(
            @PathVariable("article_id") String id
    ) {
        //根据文章id删除评论
        QueryWrapper<ArticleComment> wrapper= new QueryWrapper<ArticleComment>();
        wrapper.eq("article_id",id);
        System.out.println(id);

        boolean res = false;
        try {
            articleCommentMapper.delete(wrapper);
            res = articleMapper.delete(new QueryWrapper<Article>().eq("article_id", id))==1;
        } catch (Exception e) {
            throw new RuntimeException("删除失败");
        }

        if (res) {
            return ResultUtil.success();
        }else{
            return ResultUtil.error(500,"删除失败");
        }
    }

    //暂时无用

    /**
     * 根据id修改文章
     * @param article
     * @return
     */
    @ApiOperation(value = "根据uid修改文章")
    @Authentication(role = UserEnums.ADMIN)
    @PostMapping("/updateArticleById")
    public ResultMessage<Integer> updateArticleById(
            @RequestBody Article article
    ) {
        QueryWrapper<ArticleClass> wrapper= new QueryWrapper<ArticleClass>();
        wrapper.eq("name", article.getSortClass());
        ArticleClass articleClass = articleClassMapper.selectOne(wrapper);
        article.setUpdateTime(new Date());
        article.setSortClass(articleClass.getId().toString());
        try{
            this.articleMapper.update(article,new QueryWrapper<Article>().eq("article_id",article.getArticleId()));
        }catch (Exception e) {
            return ResultUtil.error(500, "修改失败");
        }
        return ResultUtil.success();
    }

    /**
     *  根据id获取文章
     * @param id
     * @return
     */
    @ApiOperation(value = "根据uid获取文章")
    @Authentication(role = UserEnums.ADMIN)
    @GetMapping("/getArticleById/{id}")
    public ResultMessage<Article> getArticleById(
            @PathVariable("id") String id
    ) {
        Article article = articleMapper.selectOne(new QueryWrapper<Article>().eq("article_id", id));
        String sortClass = article.getSortClass();
        QueryWrapper<ArticleClass> wrapper = new QueryWrapper<>();
        wrapper.eq("id",sortClass);
        ArticleClass articleClass = articleClassMapper.selectOne(wrapper);
        String name = articleClass.getName();
        Article articleBuffer = new Article();
        BeanUtils.copyProperties(article,articleBuffer);
        articleBuffer.setSortClass(name);
        return ResultUtil.data(articleBuffer);
    }

    /**
     * 获取所有文章
     * @param page
     * @param limit
     * @return
     */
    @ApiOperation(value = "获取所有文章")
    @Authentication(role = UserEnums.ADMIN)
    @GetMapping("/getAllArticle/{page}/{limit}")
    public ResultMessage<ArticlePageVO> getAllArticle(
            @PathVariable("page") Integer page,
            @PathVariable("limit") Integer limit
    ) {
        return ResultUtil.data(articleService.VoList(page,limit,0));
    }

    @ApiOperation(value = "获得文章数量")
    @GetMapping("getArticleCount")
    public ResultMessage<Integer> getArticleCount(){
        return ResultUtil.data(articleService.count());
    }
}
